﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Data.ConnectionUI;
using System.Xml;
using System.Data.SqlClient;
using System.IO;
using Ionic.Zip;

namespace RuleCode.ObjectTree
{
    public partial class UpdateConfigureForm : Form
    {
        #region 属性
        /// <summary>
        /// 获取或设置 是编辑配置信息还是新建配置信息
        /// </summary>
        public bool IsNew
        {
            get;
            set;
        }

        /// <summary>
        /// 获取或设置 当前配置的名称
        /// </summary>
        public string CurrentConfigureName
        {
            get;
            set;
        }

        public string ConnectStringID
        {
            get;
            set;
        }
        #endregion

        #region 构造方法
        public UpdateConfigureForm()
        {
            InitializeComponent();
            IsNew = true ;
        }
        #endregion

        #region 窗体加载
        private void UpdateConfigureForm_Load(object sender, EventArgs e)
        {
            this.Text = IsNew ? "增加新的配置" : "修改配置--"+CurrentConfigureName ;
            InitCurrentConfigure();
        }
        #endregion

        #region 事件
        private void Button_ModulePath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog_ModulePath.ShowDialog();  
            if (FolderBrowserDialog_ModulePath.SelectedPath != string.Empty)
            {
                TextBox_ModulePath.Text = FolderBrowserDialog_ModulePath.SelectedPath;
            }
        }

        private void Button_OTPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog_OTPath.ShowDialog();
            if (FolderBrowserDialog_OTPath.SelectedPath != string.Empty)
            {
                TextBox_OTPath.Text = FolderBrowserDialog_OTPath.SelectedPath;
            }
        }

        private void Button_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Button_OK_Click(object sender, EventArgs e)
        {
            if (ValidateParams())
            {
                SaveConfigure(false);
                this.Close();
            }
        }

        private void Button_SaveASCurrentConfi_Click(object sender, EventArgs e)
        {
            if (ValidateParams())
            {
                SaveConfigure(true);
                this.Close();
            }
        }

        private void Button_ConfigDataBase_Click(object sender, EventArgs e)
        {
            //Microsoft.Data.ConnectionUI.DataConnectionDialog _dialog = new  Microsoft.Data.ConnectionUI.DataConnectionDialog();
           
            //_dialog.DataSources.Add(DataSource.SqlDataSource);
            //_dialog.SelectedDataSource = DataSource.SqlDataSource;
            //_dialog.SelectedDataProvider = DataProvider.SqlDataProvider;
            //if (Microsoft.Data.ConnectionUI.DataConnectionDialog.Show(_dialog) == DialogResult.OK)
            //{
            //    this.TextBox_SqlConnectStr  .Text = _dialog.ConnectionString;
            //}
            //_dialog.Dispose();
            DataBaseConfig dataBaseConfig = new DataBaseConfig();
            dataBaseConfig.ShowDialog();
            string cnnID = dataBaseConfig.ConnectStringID;
            if (!string.IsNullOrEmpty(cnnID))
            {
                ConnectStringID = cnnID;
                string cnnStr = Util.GetConnectString(cnnID);
                TextBox_SqlConnectStr.Text = cnnStr;
            }
            else
            {
                TextBox_SqlConnectStr.Text = string.Empty;
            }
        }
        #endregion

        #region　辅助方法
        /// <summary>
        /// 保存配置
        /// </summary>
        private void SaveConfigure( bool setCurrentConfig)
        {
            string oldOTPath = string.Empty;
            string oldModulePath = string.Empty;
            string cur_name = TextBox_Name.Text.Trim();

            string profileFileName =Util.GetProfilePath();
            XmlDocument aots = new XmlDocument();
            aots.Load(profileFileName);
            XmlNode aotsnode = aots.SelectSingleNode("//aots");

            XmlNode childNode = aots.CreateElement("aot");
            XmlAttribute attrNode = aots.CreateAttribute("Name");
            attrNode.Value = TextBox_Name.Text;
            childNode.Attributes.Append(attrNode);

            attrNode = aots.CreateAttribute("cnnStringID");
            attrNode.Value =ConnectStringID ;
            childNode.Attributes.Append(attrNode);


            attrNode = aots.CreateAttribute("OTPath_Module");
            oldModulePath = attrNode.Value;
            attrNode.Value = TextBox_ModulePath.Text;
            childNode.Attributes.Append(attrNode);

            attrNode = aots.CreateAttribute("OTPath");
            oldOTPath = attrNode.Value;
            attrNode.Value = TextBox_OTPath.Text;
            childNode.Attributes.Append(attrNode);



            if (IsNew)
            {
                string configName = TextBox_Name.Text;
                XmlNodeList nodes = aots.SelectNodes("//aot[@Name='" + configName + "']");
                if (nodes.Count > 0)
                {
                    MessageBox.Show("对不起，已经存在名称为:" + configName + " 的配置，请重新命名！");
                    return;
                }
                aotsnode.AppendChild(childNode);

                string configOTPath = Util.GetUserDataPath()+GlobalStaticDirectoryPath.AOTSProfilePath +"\\"+ configName;
                configOTPath = Path.Combine(configOTPath, Util.DevArea);
                //unpack all templates
                Util.UnpackTempaltes(TextBox_Name.Text, configOTPath);
                Util.UnpackLabelFiles(configOTPath);     

            }
            else
            {
                string configName = TextBox_Name.Text;
                XmlNode node = aots.SelectSingleNode ("//aot[@Name='" + configName + "']");
                if (node != null)
                {
                    aotsnode.RemoveChild(node);
                    aotsnode.AppendChild(childNode);
                }

                //如果更改了 OTPath后，解压模板，拷贝LabelFile文件
                if (TextBox_OTPath.Text.Trim() != oldOTPath.Trim())
                {
                    string newOTPath = TextBox_OTPath.Text.Trim();
                    if (newOTPath == string.Empty)
                        newOTPath = Util.GetUserDataPath() + GlobalStaticDirectoryPath.AOTSProfilePath + "\\" + cur_name + "\\" + Util.DevArea;
                    if(String.IsNullOrEmpty (oldOTPath ))
                        oldOTPath =  Util.GetUserDataPath() + GlobalStaticDirectoryPath.AOTSProfilePath + "\\" + cur_name + "\\" + Util.DevArea;
                    if (Directory.Exists(TextBox_OTPath.Text) && Directory.Exists(oldOTPath))
                    {
                        FileOperator.CopyFolder(Path.Combine(oldOTPath, GlobalStaticDirectoryPath.Templates.Trim("\\".ToCharArray())),
                                                  Path.Combine(newOTPath, GlobalStaticDirectoryPath.Templates.Trim("\\".ToCharArray())));
                        FileOperator.CopyFolder(Path.Combine(oldOTPath, GlobalStaticDirectoryPath.LabelFile.Trim("\\".ToCharArray())),
                                                  Path.Combine(newOTPath, GlobalStaticDirectoryPath.LabelFile.Trim("\\".ToCharArray())));
                        FileOperator.CopyFolder(Path.Combine(oldOTPath, GlobalStaticDirectoryPath.ObjectData.Trim("\\".ToCharArray())),
                                                  Path.Combine(newOTPath, GlobalStaticDirectoryPath.ObjectData.Trim("\\".ToCharArray ())));
                        if(File.Exists (Path.Combine (oldOTPath ,GlobalStaticDirectoryPath .AOTFileXml ))  )
                            File.Copy (Path.Combine (oldOTPath ,GlobalStaticDirectoryPath.AOTFileXml ),
                                       Path.Combine(newOTPath, GlobalStaticDirectoryPath.AOTFileXml));
                        if (File.Exists(Path.Combine(oldOTPath, GlobalStaticDirectoryPath.AOTFileBakXML )))
                            File.Copy(Path.Combine(oldOTPath, GlobalStaticDirectoryPath.AOTFileBakXML),
                                       Path.Combine(newOTPath, GlobalStaticDirectoryPath.AOTFileBakXML));   
                    }
                }

                //更改了ModulePath，则拷贝相应的AOTFiles
                if (TextBox_ModulePath.Text.Trim() != oldModulePath.Trim())
                {
                    string newModulePath = TextBox_ModulePath.Text.Trim ();
                    if (newModulePath == string.Empty)
                        newModulePath = Util.GetUserDataPath() + GlobalStaticDirectoryPath.AOTSProfilePath + "\\" + cur_name  + "\\" +Util . DevArea + GlobalStaticDirectoryPath.ModulePath.TrimEnd("\\".ToCharArray());
                    if(String.IsNullOrEmpty (oldModulePath ))
                        oldModulePath =   Util.GetUserDataPath() + GlobalStaticDirectoryPath.AOTSProfilePath + "\\" + cur_name  + "\\" +Util . DevArea + GlobalStaticDirectoryPath.ModulePath.TrimEnd("\\".ToCharArray());
                    if (Directory.Exists(newModulePath) && Directory.Exists(oldModulePath))
                    {
                        DirectoryInfo dInfo = new DirectoryInfo(oldModulePath);
                        FileInfo[] allFiles = dInfo.GetFiles();
                        foreach (FileInfo fInfo in allFiles)
                        {
                            string toFileName = Path.Combine(newModulePath, fInfo.Name);  
                            fInfo.CopyTo(toFileName, true);
                        }
                    }
                }
            }

            aots.Save(profileFileName);

            //设置为当前配置
            if (setCurrentConfig)
            {

                Util.SetCurrentProfileName(TextBox_Name.Text);
                Util.SetBack();
                Util.InitCurrentProfileName();
                Util.InitOTPath();

               
            }         
        }

       

        /// <summary>
        /// 验证输入的参数
        /// </summary>
        /// <returns></returns>
        private bool ValidateParams()
        {
            bool result = true ;
            if (String.IsNullOrEmpty(TextBox_Name.Text.Trim()))
            {
                MessageBox.Show("名称不能为空！");
                return false;
            }
            if (String.IsNullOrEmpty(TextBox_SqlConnectStr.Text))
            {
                MessageBox.Show("数据库链接字符串配置不能为空！");
                return false;
            }
            else
            {
                string sqlConnectStr = TextBox_SqlConnectStr.Text; 
                SqlConnection sqlCon = null ;
                try
                {
                    sqlCon = new SqlConnection(sqlConnectStr);
                }catch{}
                if ((sqlCon != null) && (!string.IsNullOrEmpty(sqlCon.Database)))
                {
                    return true;
                }
                else
                {
                    MessageBox.Show("链接字符串不正确！");
                    return false;
                }

            }
            return result;
        }

        /// <summary>
        /// 初始化 配置（当修改配置的时候）
        /// </summary>
        private void InitCurrentConfigure()
        {
            if (!IsNew && !String.IsNullOrEmpty(CurrentConfigureName))
            {
                XmlDocument  aots = new XmlDocument();
                aots.Load(Util.GetProfilePath());
                XmlNode aotsnode = aots.SelectSingleNode("//aots");
                XmlNode node = aots.SelectSingleNode("//aot[@Name='" + CurrentConfigureName + "']");
                if (node != null)
                {
                    try
                    {
                        TextBox_Name.Text = node.Attributes.GetNamedItem("Name").Value;
                    }
                    catch { }
                    try
                    {
                        this.TextBox_OTPath.Text = node.Attributes.GetNamedItem("OTPath").Value;
                    }
                    catch { }
                    try
                    {
                        this.TextBox_ModulePath.Text = node.Attributes.GetNamedItem("OTPath_Module").Value;
                    }
                    catch { }
                    try
                    {
                        string cnnStrID = node.Attributes.GetNamedItem("cnnStringID").Value;
                        if (!String.IsNullOrEmpty(cnnStrID))
                        {
                            ConnectStringID = cnnStrID;
                            XmlNode cnnNode = node.SelectSingleNode("//cnnString[@ID='"+cnnStrID +"']");
                            if(cnnNode !=null && cnnNode.Attributes .GetNamedItem ("Value")!=null)
                                this.TextBox_SqlConnectStr.Text = cnnNode.Attributes.GetNamedItem("Value").Value;
                        }
                    }
                    catch { }
                }
            }
        }
        #endregion
    }
}
